import React, {useEffect, useRef} from "react";

export interface TextEditorProps {
    defaultValue?: string;
    onCommit?: (val:any) => void;
}

const textEditor: React.FC<TextEditorProps> = ({defaultValue, onCommit}) => {
    const editorRef = useRef<HTMLInputElement>(null);
    useEffect(() => {
        if (editorRef.current) {
            editorRef.current.focus();
            editorRef.current.select();
        }
    }, [editorRef]);
    const [value, setValue] = React.useState(defaultValue);
    const keyDownHanle = (e:React.KeyboardEvent)=>{
        if(e.code == 'Enter') {
            onCommit && onCommit(value)
            e.stopPropagation(); // 阻止事件冒泡
        }
    }
    return (
        <input type="text" onKeyDown={keyDownHanle} style={{width: '100%'}} ref={editorRef} value={value} onChange={(e) => setValue(e.target.value)}/>
    )
}

export default textEditor